/*
 * CenterMassBW2.cpp
 *
 *  Created on: Jan 9, 2015
 *      Author: marchi
 */

#include "CenterMassBW2.h"

void CenterMassBW2::WriteIt(ostream & fout) {
	vector<double> t(cm.size()*DIM);
	vector<double> v;
	for(auto q: Q_t){
		Quaternion qq=q.normalized();
		v.push_back(qq[0]);
		v.push_back(qq[1]);
		v.push_back(qq[2]);
		v.push_back(qq[3]);
	}
	auto n=0;
	for(auto v: cm)
		for(auto q=0;q<DIM;q++)
			t[n++]=v[q];
	int r=cm.size();
	vector<int> rr(r);
	for(auto i=0;i<r;i++) rr[i]=cmm[i].size();
	auto nn=accumulate(rr.begin(),rr.end(),0);
	vector<double> tmR(nn*DIM);
	vector<double> tmL(nn*DIM);

	double time=CenterMass::getTime();
	vector<vector<Dvect> > cmL=cmm;
	vector<vector<Dvect> > cmR=cmm;
	RotateBack(cmR);

	auto po=[](vector<double> & x,vector<vector<Dvect> > & y){
		auto p=0;for(auto & R0: y)
			for(auto & R1: R0)
				for(auto m=0;m<DIM;m++)
					x[p++]=R1[m]; };
	po(tmR,cmR);
	po(tmL,cmL);

	fout.write((char *) &time, sizeof time);
	fout.write((char *) &r, sizeof r);
	fout.write((char *) &rr[0], (sizeof rr[0])*r);
	fout.write(reinterpret_cast<const char *> (&CO), sizeof(Matrix));
	fout.write(reinterpret_cast<const char *> (&OC), sizeof(Matrix));
	fout.write((char *) &t[0], (sizeof t[0])*r*DIM);
	fout.write((char *) &v[0], (sizeof v[0])*r*(DIM+1));
	fout.write((char *) &tmR[0], (sizeof tmR[0])*nn*DIM);
	fout.write((char *) &tmL[0], (sizeof tmL[0])*nn*DIM);
}


CenterMassBW2::CenterMassBW2() {
}
CenterMassBW2::~CenterMassBW2() {
	// TODO Auto-generated destructor stub
}
void CenterMassBW2::operator ()(vector<Dvect> & v,  vector<vector<Dvect> > & vm, vector<Quaternion> & Q) {
	CenterMass::operator()(v,Q);
	for(auto i=0;i<vm.size();i++){
		try{if(DoneOnce) if(cmm[i].size() != vm[i].size()) throw "The number of molecules in clusters changes from step to step!! ";}
		catch(const char * s){cout << s <<endl;exit(1);}
		cmm[i]=vm[i];
	}
	DoneOnce=true;
}
